﻿using System;
using System.Collections;
using System.Windows;
using System.Windows.Threading;
using PeoplesJukebox.Web.Enums;
using PeoplesJukebox.Web.ServiceClients.Bases;

namespace PeoplesJukebox.Web.Pages
{
    /// <summary>
    /// Application start page
    /// </summary>
    /// <remarks>
    /// Shown when the app is first loaded. If the media player is idle, 
    /// shows the Start button and waits. If the media player is playing, 
    /// shows the Restart button to reset the player and skips the page if
    /// the user does not respond - ensuring no mistaken restarts
    /// </remarks>
    public partial class StartPage : PageBase
    {
        private DispatcherTimer WaitTimer { get; set; }

        /// <summary>
        /// Returns the page type
        /// </summary>
        public override PageType PageType
        {
            get { return PageType.Start; }
        }

        /// <summary>
        /// Default constructor
        /// </summary>
        public StartPage()
        {
            InitializeComponent();
            this.PlayerServiceClient.SearchComplete += new ServiceClientBase.SearchCompleteEventHandler(PlayerServiceClient_SearchComplete);
            this.PlayerServiceClient.GetCurrentTrack();
        }

        private void PlayerServiceClient_SearchComplete(IEnumerable results)
        {
            //if there's a current track, only show this page temporarily:
            if (results != null)
            {
                IEnumerator enumerator = results.GetEnumerator();
                if (enumerator.MoveNext())
                {
                    this.startButton.Text = "Restart";
                    this.WaitTimer = new DispatcherTimer();
                    this.WaitTimer.Interval = new TimeSpan(0, 0, 5);
                    this.WaitTimer.Tick += new EventHandler(WaitTimer_Tick);
                    this.WaitTimer.Start();
                }
            }
        }

        private void WaitTimer_Tick(object sender, EventArgs e)
        {
            this.Complete();
        }

        private void Button_Click(object sender, RoutedEventArgs e)
        {
            this.PlayerServiceClient.Start();
            this.Complete();
        }

        private void Complete()
        {
            if (this.WaitTimer != null)
            {
                this.WaitTimer.Stop();
                this.WaitTimer = null;
            }
            this.Completed(PageType.Home);
        }
    }
}